import { api } from "@/lib/request";
import type { Provider } from "@/types/oauth";
import type { Response } from "@/types/response";

export interface OAuthLoginRequest {
  provider: Provider;
}

export interface OAuthLoginResponseData {
  auth_url: string;
}

export interface OAuthProviderInfo {
  provider: Provider;
  name: string;
  enabled: boolean;
  linked: boolean;
  email?: string;
  user_name?: string;
}

export interface OAuthUnlinkRequest {
  provider: Provider;
}

export interface OAuthUnlinkResponseData {
  unlinked: boolean;
}

export interface OAuthSetPrimaryEmailRequest {
  provider: Provider;
}

export interface OAuthSetPrimaryEmailResponseData {
  updated: boolean;
}

// OAuth API
export const oauthAPI = {
  /**
   * 发起 OAuth 登录
   */
  login: async (
    provider: Provider
  ): Promise<Response & { data: OAuthLoginResponseData }> => {
    const response = await api.post("/oauth/login", { provider });
    return response as unknown as Response & { data: OAuthLoginResponseData };
  },

  /**
   * 获取 OAuth 提供商列表
   */
  getProviders: async (): Promise<Response & { data: OAuthProviderInfo[] }> => {
    const response = await api.get("/oauth/providers");
    return response as unknown as Response & { data: OAuthProviderInfo[] };
  },

  /**
   * 解绑 OAuth 提供商
   */
  unlink: async (
    data: OAuthUnlinkRequest
  ): Promise<Response & { data: OAuthUnlinkResponseData }> => {
    const response = await api.post("/oauth/unlink", data);
    return response as unknown as Response & { data: OAuthUnlinkResponseData };
  },

  /**
   * 设置 OAuth 邮箱为主邮箱
   */
  setPrimaryEmail: async (
    data: OAuthSetPrimaryEmailRequest
  ): Promise<Response> => {
    const response = await api.post("/oauth/set-primary-email", data);
    return response as unknown as Response;
  },
};
